package com.bestcem.xm.qdes.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bestcem.xm.qdes.controller.param.ProjectFinishParam;
import com.bestcem.xm.qdes.entity.QdesProject;
import com.bestcem.xm.qdes.mapper.QdesProjectMapper;
import com.bestcem.xm.qdes.service.QdesFinishProjectService;
import com.bestcem.xm.qdes.service.QdesProjectService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.bestcem.xm.qdes.grpc.v1.services.ProjectStatus.PROJECT_STATUS_ACTIVATED;

@Slf4j
@Service
@RequiredArgsConstructor
public class QdesFinishProjectServiceImpl implements QdesFinishProjectService {

    private @NonNull QdesProjectMapper qdesProjectMapper;

    private @NonNull QdesProjectService projectService;

    @Override
    public void finishProject() {
        //当前时间秒
        long now = DateUtil.currentSeconds();
        List<QdesProject> projects = qdesProjectMapper.selectList(new LambdaQueryWrapper<QdesProject>()
                .gt(QdesProject::getTimerExpire, now - 24 * 3600)
                .lt(QdesProject::getTimerExpire, now));
        projects.forEach(proj -> {
            Integer expire = proj.getTimerExpire();
            String attrStr = proj.getCustomAttr();
            JSONObject attr = JSONObject.parseObject(attrStr);
            if (attr.getBooleanValue("time_flag")) {
                long end_time = attr.getLongValue("end_time");
                if (proj.getStatus() == PROJECT_STATUS_ACTIVATED.getNumber()) {
                    //# 发布中
                    if (ObjectUtil.isNotEmpty(end_time) && (end_time / 1000 == expire)) {
                        ProjectFinishParam param = new ProjectFinishParam();
                        param.setProjectId(proj.getId());
                        projectService.finishProject(param);
                    }
                }
            }
            //QdesProject project = qdesProjectMapper.selectById(proj.getId());
            //project.setTimerExpire(null);
            //qdesProjectMapper.alwaysUpdateSomeColumnById(project);

            qdesProjectMapper.update(
                    null,
                    Wrappers.<QdesProject>lambdaUpdate()
                            .set(QdesProject::getUpdatedDt, LocalDateTime.now())
                            .set(QdesProject::getTimerExpire, null)
                            .eq(QdesProject::getId, proj.getId())
            );
        });
    }
}
